package cn.apthink.solon;

import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Action;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;

import cn.apthink.model.ActionLog;
import cn.apthink.utility.DateUtil;
import cn.dev33.satoken.stp.StpUtil;

//定义会话处理拦截器
@Component(index = -99)
public class ActionLogInterceptor implements RouterInterceptor {
	@Override
	public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
		if (StpUtil.isLogin()) {
			Action action = ctx.action();
			ActionLog log = (ActionLog) StpUtil.getTokenSession().get("latestaction");
			log.setMethod(action.method().getName());
			log.setController(action.method().getDeclaringClz().getName());
			log.setStarttime(DateUtil.now());
			log.setEndtime(null);
			log.setConsumedtime(0);
			// 1.开始计时
			long start = System.currentTimeMillis();
			try {
				chain.doIntercept(ctx, mainHandler);
			} finally {
				// 2.获得接口响应时长
				long timespan = System.currentTimeMillis() - start;
				log.setConsumedtime(timespan);
				log.setEndtime(DateUtil.now());
				// 3.保存操作日志
				// logService.saveActionLog(log);。
			}
		} else {
			chain.doIntercept(ctx, mainHandler);
		}
	}
}
